import { useEffect, useRef, useState } from "react";
import { Button, Input, message } from "antd";
import Password from "antd/es/input/Password";
import { EyeInvisibleOutlined, EyeOutlined, LockOutlined, UserOutlined } from '@ant-design/icons';
import RequestApis from "../../../apis/requestApis";
import RequestUtils from "../../../utils/requestUtils";
import TokenUtils from "../../../utils/tokenUtils"
import { useNavigate } from "react-router-dom";

const LoginPage = () => {
    const navigate = useNavigate();
    const canvasRef = useRef(null);

    const [passwordVisible, setPasswordVisible] = useState(false);
    const [messageApi, contextHolder] = message.useMessage();

    const [loginParams, setLoginParams] = useState({
        userAccount: "",
        password: "",
    });

    const doLogin = (routeType) => {
        if (routeType === "front") {
            messageApi.error("暂未开放！");
            return;
        }

        RequestUtils.post(RequestApis.userAuth.login, {
            userAccount: loginParams.userAccount,
            userPassword: loginParams.password,
            clientType: 0
        }).then(res => {
            TokenUtils.saveUserToken(res.data.data.token);
            TokenUtils.saveUserIdAndNickname(res.data.data.id, res.data.data.userNickname)
            TokenUtils.saveUserPagePermissionCodes(res.data.data.pagePermissionCodes)
            messageApi.success("登录成功，即将跳转到控制台！")
                .then(r => {
                    navigate("/console/index")
                });
        }).catch(err => {
            messageApi.error(err.message);
        })
    }

    useEffect(() => {
        const style = document.createElement('style');
        style.innerHTML = `
      .ant-input::placeholder,
      .ant-input-affix-wrapper::placeholder {
        color: rgba(255, 255, 255, 0.6) !important;
        opacity: 1 !important;
      }
      
      .ant-input::-webkit-input-placeholder,
      .ant-input-affix-wrapper::-webkit-input-placeholder {
        color: rgba(255, 255, 255, 0.6) !important;
      }
      
      .ant-input:-moz-placeholder,
      .ant-input-affix-wrapper:-moz-placeholder {
        color: rgba(255, 255, 255, 0.6) !important;
        opacity: 1 !important;
      }
      
      .ant-input::-moz-placeholder,
      .ant-input-affix-wrapper::-moz-placeholder {
        color: rgba(255, 255, 255, 0.6) !important;
        opacity: 1 !important;
      }
      
      .ant-input:-ms-input-placeholder,
      .ant-input-affix-wrapper:-ms-input-placeholder {
        color: rgba(255, 255, 255, 0.6) !important;
      }
      
      .ant-input-password-icon {
        color: rgba(255, 255, 255, 0.6) !important;
        transition: color 0.3s ease;
      }
      
      .ant-input-password-icon:hover {
        color: rgba(255, 255, 255, 1) !important;
      }
      
      input:-webkit-autofill,
      input:-webkit-autofill:hover,
      input:-webkit-autofill:focus,
      input:-webkit-autofill:active,
      .ant-input-affix-wrapper:-webkit-autofill,
      .ant-input-affix-wrapper:-webkit-autofill:hover,
      .ant-input-affix-wrapper:-webkit-autofill:focus {
        -webkit-text-fill-color: rgba(255, 255, 255, 0.9) !important;
        -webkit-box-shadow: 0 0 0px 1000px rgba(255, 255, 255, 0.08) inset !important;
        box-shadow: 0 0 0px 1000px rgba(255, 255, 255, 0.08) inset !important;
        background-color: transparent !important;
        background-image: none !important;
        transition: background-color 5000s ease-in-out 0s !important;
      }

      .login-card {
        transform: translateY(0);
        transition: all 0.5s cubic-bezier(0.16, 1, 0.3, 1);
      }
      
      .login-card:hover {
        transform: translateY(-5px);
      }

      .btn-primary {
        position: relative;
        overflow: hidden;
      }
      
      .btn-primary::after {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        width: 300%;
        height: 300%;
        background: rgba(255, 255, 255, 0.1);
        transform: translate(-50%, -50%) rotate(45deg);
        transition: all 0.75s ease;
      }
      
      .btn-primary:hover::after {
        width: 0;
        height: 0;
      }
    `;
        document.head.appendChild(style);

        return () => {
            document.head.removeChild(style);
        };
    }, []);

    useEffect(() => {
        const canvas = canvasRef.current;
        if (!canvas) return;

        const ctx = canvas.getContext('2d');
        let width = window.innerWidth;
        let height = window.innerHeight;

        canvas.width = width;
        canvas.height = height;

        class Particle {
            constructor() {
                this.x = Math.random() * width;
                this.y = Math.random() * height;
                this.size = Math.random() * 2.5 + 0.5;
                this.speedX = (Math.random() - 0.5) * 0.8;
                this.speedY = (Math.random() - 0.5) * 0.8;
                this.color = this.getRandomNeonColor();
            }

            getRandomNeonColor() {
                const colors = [
                    'rgba(138, 43, 226, 0.7)', // 靛蓝色
                    'rgba(75, 0, 130, 0.7)',   // 靛蓝色深
                    'rgba(0, 255, 255, 0.6)',  // 青色
                    'rgba(147, 112, 219, 0.7)',// 中紫色
                    'rgba(230, 230, 250, 0.6)' // lavender
                ];
                return colors[Math.floor(Math.random() * colors.length)];
            }

            update() {
                this.x += this.speedX;
                this.y += this.speedY;

                if (this.x > width) this.x = 0;
                if (this.x < 0) this.x = width;
                if (this.y > height) this.y = 0;
                if (this.y < 0) this.y = height;
            }

            draw() {
                ctx.fillStyle = this.color;
                ctx.beginPath();
                ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
                ctx.fill();
            }
        }

        const particlesArray = [];
        const numberOfParticles = 70;

        for (let i = 0; i < numberOfParticles; i++) {
            particlesArray.push(new Particle());
        }

        const connectParticles = () => {
            for (let a = 0; a < particlesArray.length; a++) {
                for (let b = a; b < particlesArray.length; b++) {
                    const dx = particlesArray[a].x - particlesArray[b].x;
                    const dy = particlesArray[a].y - particlesArray[b].y;
                    const distance = Math.sqrt(dx * dx + dy * dy);

                    if (distance < 110) {
                        ctx.beginPath();
                        ctx.strokeStyle = `rgba(200, 150, 255, ${0.12 - distance / 2000})`;
                        ctx.lineWidth = 0.5;
                        ctx.moveTo(particlesArray[a].x, particlesArray[a].y);
                        ctx.lineTo(particlesArray[b].x, particlesArray[b].y);
                        ctx.stroke();
                    }
                }
            }
        };

        const animate = () => {
            ctx.clearRect(0, 0, width, height);

            for (let i = 0; i < particlesArray.length; i++) {
                particlesArray[i].update();
                particlesArray[i].draw();
            }

            connectParticles();
            requestAnimationFrame(animate);
        };

        animate();

        const handleResize = () => {
            width = window.innerWidth;
            height = window.innerHeight;
            canvas.width = width;
            canvas.height = height;
        };

        window.addEventListener('resize', handleResize);
        return () => window.removeEventListener('resize', handleResize);
    }, []);

    return (
        <div style={{
            position: 'relative',
            width: '100vw',
            height: '100vh',
            overflow: 'hidden',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: '#0f0024'
        }}>
            {/* 粒子背景 */}
            <canvas
                ref={canvasRef}
                style={{
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    zIndex: 0
                }}
            />

            {/* 霓虹光效叠加层 */}
            <div style={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                height: '100%',
                background: 'radial-gradient(circle at 50% 50%, rgba(147, 112, 219, 0.18) 0%, transparent 70%)',
                zIndex: 1
            }} />

            {/* 装饰性霓虹光效 */}
            <div style={{
                position: 'absolute',
                top: '-30%',
                right: '-20%',
                width: '60%',
                height: '60%',
                background: 'rgba(138, 43, 226, 0.12)',
                borderRadius: '50%',
                filter: 'blur(90px)',
                zIndex: 1,
                animation: 'pulse 15s infinite ease-in-out'
            }} />
            <div style={{
                position: 'absolute',
                bottom: '-20%',
                left: '-10%',
                width: '50%',
                height: '50%',
                background: 'rgba(0, 255, 255, 0.12)',
                borderRadius: '50%',
                filter: 'blur(90px)',
                zIndex: 1,
                animation: 'pulse 18s infinite ease-in-out 2s'
            }} />

            {contextHolder}

            {/* 登录卡片 */}
            <div className="login-card" style={{
                position: 'relative',
                zIndex: 2,
                width: '90%',
                maxWidth: '420px',
                padding: '50px 40px',
                background: 'rgba(15, 5, 30, 0.88)',
                borderRadius: '24px',
                boxShadow: '0 8px 32px rgba(75, 0, 130, 0.25), 0 0 60px rgba(138, 43, 226, 0.15)',
                backdropFilter: 'blur(16px)',
                border: '1px solid rgba(255, 255, 255, 0.08)'
            }}>
                {/* 标题 */}
                <div style={{
                    textAlign: 'center',
                    marginBottom: '40px',
                    color: 'white'
                }}>
                    <div style={{
                        width: '80px',
                        height: '80px',
                        margin: '0 auto 20px',
                        borderRadius: '50%',
                        background: 'linear-gradient(135deg, #8a2be2, #00ffff)',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        boxShadow: '0 0 25px rgba(138, 43, 226, 0.35)'
                    }}>
                        <LockOutlined style={{ fontSize: '32px', color: 'white' }} />
                    </div>
                    <h1 style={{
                        fontSize: '32px',
                        margin: 0,
                        background: 'linear-gradient(90deg, #b19cd9, #00ffff)',
                        WebkitBackgroundClip: 'text',
                        WebkitTextFillColor: 'transparent',
                        textShadow: '0 0 15px rgba(177, 156, 217, 0.6)'
                    }}>
                        系统登录
                    </h1>
                    <p style={{
                        color: 'rgba(200, 180, 255, 0.7)',
                        marginTop: '10px',
                        fontSize: '15px'
                    }}>
                        请输入账号密码登录系统
                    </p>
                </div>

                {/* 表单内容 */}
                <div style={{
                    display: 'flex',
                    flexDirection: 'column',
                    gap: '24px'
                }}>
                    {/* 账号输入 */}
                    <div>
                        <Input
                            value={loginParams.userAccount}
                            onChange={(e) => {
                                setLoginParams({
                                    ...loginParams,
                                    userAccount: e.target.value
                                })
                            }}
                            autoComplete="off"
                            autoCapitalize="none"
                            autoCorrect="off"
                            inputMode="text"
                            prefix={<UserOutlined style={{ color: 'rgba(200, 180, 255, 0.7)' }} />}
                            style={{
                                backgroundColor: 'rgba(255, 255, 255, 0.08)',
                                border: '1px solid rgba(138, 43, 226, 0.3)',
                                borderRadius: '12px',
                                color: 'rgba(255, 255, 255, 0.9)',
                                height: '54px',
                                padding: '0 16px',
                                transition: 'all 0.3s ease',
                                '&:focus': {
                                    borderColor: '#b19cd9',
                                    boxShadow: '0 0 0 2px rgba(177, 156, 217, 0.25)',
                                    backgroundColor: 'rgba(255, 255, 255, 0.1)'
                                }
                            }}
                            placeholder="请输入账号"
                        />
                    </div>

                    {/* 密码输入 */}
                    <div>
                        <Password
                            value={loginParams.password}
                            onChange={(e) => {
                                setLoginParams({
                                    ...loginParams,
                                    password: e.target.value
                                })
                            }}
                            autoComplete="new-password"
                            inputMode="text"
                            visibilityToggle={{
                                visible: passwordVisible,
                                onVisibleChange: setPasswordVisible
                            }}
                            iconRender={visible => visible ?
                                <EyeOutlined style={{ color: 'rgba(200, 180, 255, 0.7)' }} /> :
                                <EyeInvisibleOutlined style={{ color: 'rgba(200, 180, 255, 0.7)' }} />
                            }
                            prefix={<LockOutlined style={{ color: 'rgba(200, 180, 255, 0.7)' }} />}
                            style={{
                                backgroundColor: 'rgba(255, 255, 255, 0.08)',
                                border: '1px solid rgba(138, 43, 226, 0.3)',
                                borderRadius: '12px',
                                color: 'rgba(255, 255, 255, 0.9)',
                                height: '54px',
                                padding: '0 16px',
                                transition: 'all 0.3s ease',
                                '&:focus': {
                                    borderColor: '#b19cd9',
                                    boxShadow: '0 0 0 2px rgba(177, 156, 217, 0.25)',
                                    backgroundColor: 'rgba(255, 255, 255, 0.1)'
                                }
                            }}
                            placeholder="请输入密码"
                        />
                    </div>

                    {/* 注册链接 */}
                    <div style={{
                        display: 'flex',
                        justifyContent: 'flex-end',
                        marginTop: '-10px'
                    }}>
            <span style={{
                color: '#b19cd9',
                cursor: 'pointer',
                fontSize: '14px',
                transition: 'all 0.3s ease',
                '&:hover': {
                    color: '#d8bfd8',
                    textDecoration: 'underline',
                    textShadow: '0 0 10px rgba(216, 191, 216, 0.5)'
                }
            }}>
              还没有账号？请点此注册
            </span>
                    </div>

                    {/* 登录按钮 */}
                    <div style={{
                        display: 'flex',
                        flexDirection: 'column',
                        gap: '16px',
                        marginTop: '10px'
                    }}>
                        <Button
                            onClick={() => doLogin("console")}
                            className="btn-primary"
                            style={{
                                width: '100%',
                                height: '54px',
                                fontSize: '16px',
                                borderRadius: '12px',
                                background: 'linear-gradient(90deg, #8a2be2, #483d8b)',
                                color: 'white',
                                border: 'none',
                                transition: 'all 0.3s ease',
                                '&:hover': {
                                    background: 'linear-gradient(90deg, #9932cc, #551a8b)',
                                    boxShadow: '0 0 20px rgba(138, 43, 226, 0.45)'
                                }
                            }}
                        >
                            登录控制台
                        </Button>

                        <Button
                            onClick={() => doLogin("front")}
                            style={{
                                width: '100%',
                                height: '54px',
                                fontSize: '16px',
                                borderRadius: '12px',
                                background: 'rgba(255, 255, 255, 0.08)',
                                color: 'rgba(255, 255, 255, 0.9)',
                                border: '1px solid rgba(138, 43, 226, 0.3)',
                                transition: 'all 0.3s ease',
                                '&:hover': {
                                    background: 'rgba(255, 255, 255, 0.12)',
                                    borderColor: 'rgba(138, 43, 226, 0.5)',
                                    boxShadow: '0 0 15px rgba(138, 43, 226, 0.15)'
                                }
                            }}
                        >
                            登录前台系统
                        </Button>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default LoginPage;